<template>
  <div class="app-container">

    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.couponTitile" clearable class="filter-item" style="width: 200px;" placeholder="请输入优惠券标题" />
      <el-select v-model="listQuery.getRules" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券类型">
        <el-option v-for="type in typeOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-select v-model="listQuery.state" clearable style="width: 200px" class="filter-item" placeholder="请选择优惠券状态">
        <el-option v-for="type in statusOptions" :key="type.value" :label="type.label" :value="type.value" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button :loading="downloadLoading" class="filter-item" type="primary" icon="el-icon-download" @click="handleDownload">导出</el-button>
        <el-button  type="primary" class="filter-item"  @click="handleUpdate(null)">新增</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table v-loading="listLoading" :data="list" element-loading-text="正在查询中。。。" border fit highlight-current-row>

      <el-table-column align="center" label="优惠券ID" prop="id" sortable />

      <el-table-column align="center" label="优惠券名称" prop="coupontitile" />

      <el-table-column align="center" label="介绍" prop="couponrulestitle" />

      <el-table-column align="center" label="优惠类型" prop="couponrules" />

      <el-table-column align="center" label="优惠限制" prop="couponrulesjudge">
        <template slot-scope="scope">满足{{ scope.row.couponrulesjudge }}可用</template>
      </el-table-column>

      <el-table-column align="center" label="优惠金额" prop="couponmoney">
        <template slot-scope="scope">减免{{ scope.row.couponmoney }}元</template>
      </el-table-column>

      <el-table-column align="center" label="每人限领" prop="repetitionget">
        <template slot-scope="scope">{{ scope.row.repetitionget }}</template>
      </el-table-column>

      <el-table-column align="center" label="使用范围" prop="scope">
        <template slot-scope="scope">{{ scope.row.scope ==='*'?'全场通用':'编辑中查看'}}</template>
      </el-table-column>

      <el-table-column align="center" label="优惠券类型" prop="getrules">
        <template slot-scope="scope">{{ scope.row.getrules}}</template>
      </el-table-column>

      <el-table-column align="center" label="优惠券数量" prop="couponscount">
        <template slot-scope="scope">{{scope.row.couponscount ===-1 ?"∞" :scope.row.couponscount}}</template>
      </el-table-column>
    <el-table-column align="center" label="过期时间设置" prop="couponsTime">
        <template slot-scope="scope">{{ scope.row.couponsTime ||0}}天</template>
      </el-table-column>
      <el-table-column align="center" label="最终过期时间" prop="stopdate">
        <template slot-scope="scope">{{ scope.row.stopdate }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state">
        <template slot-scope="scope">{{ couponState[scope.row.state]}}</template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini"  @click="handleDetail(scope.row)">详情</el-button>
          <el-button  type="primary" size="mini"  @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button  type="primary" size="mini"  @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="listQuery.infoCount>0" :total="listQuery.infoCount" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" >
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="100px" style="width: 400px; margin-left:50px;">
       <el-form-item label="优惠券id" prop="id">
         <el-input v-model="dataForm.id" :disabled="true"/>
       </el-form-item>
        <el-form-item label="优惠券名称" prop="coupontitile">
          <el-input v-model="dataForm.coupontitile" />
        </el-form-item>
        <el-form-item label="介绍" prop="couponrulestitle">
          <el-input v-model="dataForm.couponrulestitle" />
        </el-form-item>
        <el-form-item label="优惠类型" prop="couponrules">
          <el-select v-model="dataForm.couponrules" @change="scopeChange()">
            <el-option
              v-for="type in CouponRulesOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-select v-model="dataForm.state" @change="scopeChange()">
            <el-option
              v-for="type in statusOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="优惠限制" prop="couponrulesjudge">
          <el-input  v-model="dataForm.couponrulesjudge">
          </el-input>

        </el-form-item>

        <el-form-item label="满减金额" prop="couponmoney">
          <el-input v-model="dataForm.couponmoney">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="每人限领" prop="repetitionget">
          <el-input v-model="dataForm.repetitionget">
            <template slot="append">张</template>
          </el-input>
        </el-form-item>
        <el-form-item label="分发类型" prop="getrules" >
          <el-select v-model="dataForm.getrules" @change="scopeChange()">
            <el-option
              v-for="type in typeOptions"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="isLevel ===2" label="会员等级限制" prop="getrules" >
          <el-select v-model="dataForm.couponrulesjudge" @change="scopeChange()">
              <el-option
                v-for="type in levelDic"
                :key="type.value"
                :label="type.label"
                :value="type.value"
              />
            </el-select>
        </el-form-item>
        <el-form-item label="优惠券数量" prop="couponscount">
          <el-input v-model="dataForm.couponscount">
            <template slot="append">张(不填或-1等于无限张)</template>
          </el-input>
        </el-form-item>
        <el-form-item label="有效期">
          <el-radio-group v-model="dataForm.timeType">
            <el-radio-button :label="0">领券相对天数</el-radio-button>
            <el-radio-button :label="1">指定绝对时间</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="dataForm.timeType === 0">
          <el-input v-model="dataForm.couponsTime">
            <template slot="append">天</template>
          </el-input>
        </el-form-item>
        <el-form-item v-show="dataForm.timeType === 1">


          <el-col :span="11">
            <el-date-picker v-model="dataForm.stopdate" type="datetime" placeholder="选择日期" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;" />
          </el-col>
        </el-form-item>
        <el-form-item label="商品限制范围">
          <el-radio-group v-model="sel" @change="mesInfo">
            <el-radio-button :label="0" :disabled="showList.all"  >全场通用</el-radio-button>
            <el-radio-button :label="1" :disabled="showList.type"  >指定分类</el-radio-button>
            <el-radio-button :label="2" :disabled="showList.commod"  >指定商品</el-radio-button>
            <el-radio-button :label="3" >指定禁止商品</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-show="sel === 0">
          选中我就是全场通用，提交时请注意
          （分类和商品可以共用提交时保持在二者其中一个即可）
        </el-form-item>
        <el-form-item v-show="sel === 1">
          <el-cascader
            v-model="selectGoodsCategory"
            clearable
            placeholder="请选择分类名称"
            :options="goodsCategory"
            :props="goodsCategoryOptions"
          />
          <el-button @click="handleAddGoodsCategory()">添加</el-button>
          <el-table
            ref="goodsCateRelationTable"
            :data="couponCategoryList"
            style="width: 100%;margin-top: 20px"
            border
            max-height='390'
          >
            <el-table-column label="分类名称" align="center">
              <template slot-scope="scope">{{ scope.row.id }}>{{ scope.row.name }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDeleteGoodsCategory(scope.$index, scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item v-show="sel === 2 ">
          <el-select
            v-model="selectGoods"
            filterable
            remote
            reserve-keyword
            placeholder="商品名称"
          >
            <el-option
              v-for="item in goodsOptionsList"
              :key="item.categoryid"
              :label="item.commodityid"
              :value="item.categoryid"
            >
              <span style="float: left">{{ item.commodityid }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ item.categoryid }}</span>
            </el-option>
          </el-select>
          <el-button @click="handleAddGoods()">添加</el-button>
          <el-table
            ref="goodsRelationTable"
            :data="couponGoodsList"
            style="width: 100%;margin-top: 20px"
            border
            max-height='390'
          >
            <el-table-column label="商品名称" align="center">
              <template slot-scope="scope">{{ scope.row.commodityid }}</template>
            </el-table-column>
            <el-table-column label="商品编号" align="center" width="80">
              <template slot-scope="scope">{{ scope.row.categoryid }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="60">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDeleteGoods(scope.$index, scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item v-show="sel === 3 ">
          <el-select
            v-model="selectforbidScope"
            filterable
            remote
            reserve-keyword
            placeholder="商品名称"
          >
            <el-option
              v-for="item in goodsOptionsList"
              :key="item.categoryid"
              :label="item.commodityid"
              :value="item.categoryid"
            >
              <span style="float: left">{{ item.commodityid }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">NO.{{ item.categoryid }}</span>
            </el-option>
          </el-select>
          <el-button @click="forbidScopeAddGoods()">添加</el-button>
          <el-table
            ref="goodsRelationTable"
            :data="forbidScope"
            style="width: 100%;margin-top: 20px"
            border
            max-height='390'
          >
            <el-table-column label="商品名称" align="center">
              <template slot-scope="scope">{{ scope.row.commodityid }}</template>
            </el-table-column>
            <el-table-column label="商品编号" align="center" width="80">
              <template slot-scope="scope">{{ scope.row.categoryid }}</template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="60">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="handleDeleteforbidScope(scope.$index, scope.row)"
                >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>

        <el-button  type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>

<script>
import { listCoupon, createCoupon, updateCoupon, deleteCoupon ,getScopeList} from '@/api/coupon'
import { listCategory } from '@/api/category.js'
import { listGoods } from '@/api/goods.js'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

const defaultTypeOptions = [
  {
    label: '新人首单',
    value: 'NEWPEOPLE'
  },
  {
    label: '种类特卖',
    value: 'BYTYPE'
  },
  {
    label: '商品特惠',
    value: 'BYCOMMODITY'
  },
  {
    label: '会员优惠',
    value: 'SUPERDISCOUNTS'
  }
]
const defaultCouponRules = [
  {
    label: '新人首单',
    value: 'NEWPEOPLE'
  },
  {
    label: '满额优惠',
    value: 'MEET_MONEY'
  },
  {
    label: '满件优惠',
    value: 'MEET_COUNT'
  },
  {
    label: '类型促销',
    value: 'MEET_TYPE'
  },
  {
    label: '无门槛',
    value: 'NOTHRESHOLD'
  }
]
const defaultStatusOptions = [
  {
    label: '正常',
    value: 0
  },
  {
    label: '已过期',
    value: 1
  },
  {
    label: '已下架',
    value: 2
  }
]

export default {
  name: 'Coupon',
  components: { Pagination },
  filters: {
    formatType(type) {
      for (let i = 0; i < defaultTypeOptions.length; i++) {
        if (type === defaultTypeOptions[i].value) {
          return defaultTypeOptions[i].label
        }
      }
      return ''
    },
    formatGoodsType(goodsType) {
      if (goodsType === 0) {
        return '全场通用'
      } else if (goodsType === 1) {
        return '指定分类'
      } else {
        return '指定商品'
      }
    },
    formatStatus(status) {
      if (status === 0) {
        return '正常'
      } else if (status === 1) {
        return '已过期'
      } else {
        return '已下架'
      }
    }
  },
  data() {
    return {
      typeOptions: Object.assign({}, defaultTypeOptions),
      CouponRulesOptions:Object.assign({}, defaultCouponRules),
      statusOptions: Object.assign({}, defaultStatusOptions),
      list: [],
      levelDic:[
        {
          label:'普通用户',
          value:'0'
        },
        {
          label:'高级用户',
          value:'1'
        },{
          label:'特级vip用户',
          value:'2'
        },{
          label:'至尊vip用户',
          value:'3'
        },{
          label:'超级无敌vip用户',
          value:'4'
        },
      ],
      isLevel: 1,
      sel:0,
      total: 0,
      listLoading: true,
      couponState:["正常","已过期","已下架"],
      showList:{
        all:false,
        type:false,
        commod:false
      },
      updataList:{
       id :"",
       coupontitile:"",
       couponrulestitle:"",
       couponrules:"",
       couponrulesjudge:"",
       couponmoney:"",
       repetitionget:"",
       scope:"",
       getrules:"",
       couponscount:"",
       couponsTime:"",
       stopdate:"",
       state:"",
       LinkcouponCategoryList:[],
       LinkgoodsList:[],
       forbidScope:[]
      },
      listQuery: {
        page: 1,
        limit: 20,
        couponTitile: undefined,
        getRules: undefined,
        state: undefined,
        sort: 'add_time',
        order: 'desc',
        infoCount:0
      },
      dataForm: {
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        total: 0,
        discount: 0,
        min: 0,
        limit: 1,
        getrules: "",
        CouponRules:"",
        status: 0,
        goodsType: 0,
        goodsValue: [],
        timeType: 0,
        days: 0,
        startTime: null,
        endTime: null
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [
          { required: true, message: '优惠券标题不能为空', trigger: 'blur' }
        ]
      },
      downloadLoading: false,
      selectGoods: null,
      selectforbidScope:null,
      goodsOptionsList: [],
      selectGoodsCategory: null,
      goodsCategoryOptions: {
        value:'id',
        label: 'name',
      },
       goodsCategory:[],
      couponGoodsList: [],
      couponCategoryList: [],
      LinkcouponCategoryList:[],
      LinkgoodsList:[],
      superScope:0,
      forbidScope:[],
      LinkforbidScope:[]
    }
  },
  created() {

    this.getList()
    this.getScope()
  },
  methods: {
    mesInfo(){
      this.selectGoods=null
      this.selectGoodsCategory=null
      this.selectforbidScope=null
    },
    getScope(){
      getScopeList().then(request =>{
        this.goodsCategory=request.data.data.category
        this.goodsOptionsList=request.data.data.commodity
        /*console.log(request.data.data.category)
        console.log(request.data.data.commodity)*/
      })
    },
    scopeChange(){

    if(this.dataForm.getrules ==="BYTYPE" || this.dataForm.getrules ==="种类特卖"){
              this.showList.commod=true
              this.showList.type=false

    }else if(this.dataForm.getrules ==="BYCOMMODITY" || this.dataForm.getrules ==="商品特惠"){
              this.showList.type=true
              this.showList.commod=false

    }else{
              this.showList.all=false
              this.showList.commod=false
              this.showList.type=false

    }
    if(this.dataForm.getrules ==="SUPERDISCOUNTS" || this.dataForm.getrules ==="会员优惠"){
      this.isLevel=2
    }else{
      this.isLevel=1
    }
    this.sel=0
    },
    getList() {
      this.listLoading = true
      listCoupon(this.listQuery).then(res =>{
         this.listLoading = false
         this.listQuery.infoCount=res.data.data[1].infoCount
         this.list=res.data.data[0]
        console.log( this.list=res.data.data[0])
      }).catch(res =>{
         this.listLoading = false
         this.list=[]
         this.listQuery.infoCount=0
      })

    },
    handleFilter() {

      this.getList()
    },
    resetForm() {
      this.dataForm = {
        id: undefined,
        name: undefined,
        desc: undefined,
        tag: undefined,
        total: 0,
        discount: 0,
        min: 0,
        limit: 1,
        type: 0,
        status: 0,
        goodsType: 0,
        goodsValue: [],
        timeType: 0,
        days: 0,
        startTime: null,
        endTime: null
      }
      this.couponCategoryList = []
      this.couponGoodsList = []
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          if (this.dataForm.goodsType === 1) {
            this.dataForm.goodsValue = this.couponCategoryList.map(item => (item.goodsCategoryId))
          }
          if (this.dataForm.goodsType === 2) {
            this.dataForm.goodsValue = this.couponGoodsList.map(item => (item.goodsId))
          }
          createCoupon(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '创建优惠券成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response.data.errmsg
              })
            })
        }
      })
    },
    handleUpdate(row) {
      //初始化 范围
      this.couponCategoryList=[]
      this.LinkcouponCategoryList=[]

       this.couponGoodsList=[]
       this.LinkgoodsList=[]

       this.forbidScope=[]
       this.LinkforbidScope=[]

      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        if (this.dataForm.days === 0) {
          this.dataForm.daysType = 1
        } else {
          this.dataForm.daysType = 0
        }
        this.$refs['dataForm'].clearValidate()
      })

      if(row!=null){
          this.scopeChange()
        //初始化 类型范围
        let tepyList =row.couponCategoryList
        if(tepyList!=null){
            for(let i =0;i<tepyList.length;i++){
           let data =this.returnGoodsCategory(tepyList[i])
           this.couponCategoryList.push(data)
           this.LinkcouponCategoryList.push(data.id)
        }
        }

        //初始化 商品范围
        let comList =row.couponGoodsList
        if(comList!=null){
          for(let i =0;i<comList.length;i++){
            let data =this.returnGoodObj(comList[i])
            this.couponGoodsList.push(data)
            this.LinkgoodsList.push(data.categoryid)
          }
        }

        //初始和禁用范围
        let forbid =row.forbidScope
        if(forbid!=null){
          for(let i =0;i<forbid.length;i++){
            let data =this.returnGoodObj(forbid[i])
            this.forbidScope.push(data)
            this.LinkforbidScope.push(data.categoryid)
          }
        }
      }
    },
    updateData() {
      this.updataList.id=this.dataForm.id
      this.updataList.coupontitile=this.dataForm.coupontitile
      this.updataList.couponrulestitle=this.dataForm.couponrulestitle
      this.updataList.couponrules=this.dataForm.couponrules
      this.updataList.couponrulesjudge=this.dataForm.couponrulesjudge
      this.updataList.couponmoney=this.dataForm.couponmoney
      this.updataList.repetitionget=this.dataForm.repetitionget
      this.updataList.scope=this.dataForm.scope
      this.updataList.getrules=this.dataForm.getrules
      this.updataList.couponscount=this.dataForm.couponscount
      this.updataList.couponsTime=this.dataForm.couponsTime
      this.updataList.stopdate=this.dataForm.stopdate
      this.updataList.state=this.dataForm.state

      if(this.sel===0){
         this.updataList.LinkcouponCategoryList=[]
         for(let i =0;i<this.goodsCategory.length;i++){
           this.updataList.LinkcouponCategoryList.push(this.goodsCategory[i].id)

         }

          this.updataList.LinkgoodsList=[]
          for(let i =0;i<this.goodsOptionsList.length;i++){
            this.updataList.LinkgoodsList.push(this.goodsOptionsList[i].categoryid)
          }
           this.updataList.forbidScope =this.LinkforbidScope
      }else{
        this.updataList.LinkcouponCategoryList=this.LinkcouponCategoryList
        this.updataList.LinkgoodsList=this.LinkgoodsList
        this.updataList.forbidScope =this.LinkforbidScope
      }
      updateCoupon(this.updataList).then(res =>{
        console.log(res)
        if(res.data.msg === '200'){
          alert("操作成功")
          this.dialogFormVisible = false
          this.getList()
        }else if(res.data.msg ==='4001'){
         alert("操作失败")
        }
      }).catch(res =>{
        console.log(res)
        if(res.data.msg === '200'){
          alert("操作成功")
          this.dialogFormVisible = false
          this.getList()
        }else if(res.data.msg ==='4001'){
         alert("操作失败")
        }
      })
    },
    handleDelete(row) {
      let data ={
        id:row.id
      }
      console.log(data)
      deleteCoupon(data)
        .then(res => {
           if(res.data.msg === '200'){
             alert("操作成功")
             this.getList()
           }else if(res.data.msg ==='4001'){
            alert("操作失败")
           }
        })
        .catch(res => {
         console.log(res)
           if(res.data.msg === '200'){
             alert("操作成功")
             this.getList()
           }else if(res.data.msg ==='4001'){
            alert("操作失败")
           }
         })

    },
    handleDetail(row) {
      this.$router.push({ path: '/promotion/couponDetail', query: { id: row.id }})
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = [
          '优惠券ID',
          '名称',
          '内容',
          '标签',
          '最低消费',
          '减免金额',
          '每人限领',
          '优惠券数量'
        ]
        const filterVal = [
          'id',
          'name',
          'desc',
          'tag',
          'min',
          'discount',
          'limit',
          'total'
        ]
        excel.export_json_to_excel2(tHeader, this.list, filterVal, '优惠券信息')
        this.downloadLoading = false
      })
    },
    getGoodsList() {
      listGoods({ limit: 0 }).then(response => {
        const goodsList = response.data.data.list
        this.goodsOptions = []
        for (let i = 0; i < goodsList.length; i++) {
          const item = goodsList[i]
          this.goodsOptions.push({ goodsId: item.id, goodsName: item.name, goodsSn: item.goodsSn })
        }
      }).catch(() => {
        this.goodsOptions = []
      })
    },
    handleAddGoods() {
      if (this.selectGoods === null) {
        this.$message({
          message: '请先选择商品',
          type: 'warning'
        })
        return
      }

      let data =this.returnGoodObj(this.selectGoods)

       this.couponGoodsList.push(data)
       this.LinkgoodsList.push(data.categoryid)
       this.selectGoods = []
    },
    returnGoodObj(id){
      let data={}
      for(let i =0;i<this.goodsOptionsList.length;i++){

        if(this.goodsOptionsList[i].categoryid === id){
          return data={'categoryid':this.goodsOptionsList[i].categoryid,'commodityid':this.goodsOptionsList[i].commodityid}
        }
      }
      return
    },
    forbidScopeAddGoods() {
      if (this.selectforbidScope === null) {
        this.$message({
          message: '请先选择商品',
          type: 'warning'
        })
        return
      }


       let data =this.returnGoodObj(this.selectforbidScope)
       this.forbidScope.push(data)
       this.LinkforbidScope.push(data.categoryid)
       this.selectforbidScope = []
    },
    returnGoodObj(id){
      let data={}
      for(let i =0;i<this.goodsOptionsList.length;i++){

        if(this.goodsOptionsList[i].categoryid === id){
          return data={'categoryid':this.goodsOptionsList[i].categoryid,'commodityid':this.goodsOptionsList[i].commodityid}
        }
      }
      return
    },
    handleDeleteGoods(index, row) {
      this.couponGoodsList.splice(index, 1)
      this.LinkgoodsList.splice(index,1)

    },
    handleAddGoodsCategory() {

      if (this.selectGoodsCategory === null || this.selectGoodsCategory.length === 0) {
        this.$message({
          message: '请先选择商品分类',
          type: 'warning'
        })
        return
      }

      let data =this.returnGoodsCategory(this.selectGoodsCategory[0])
       this.couponCategoryList.push(data)
       this.LinkcouponCategoryList.push(data.id)
       this.selectGoodsCategory = []
    },
    returnGoodsCategory(id){/**通过id返回完整的对象 id 和 name*/
    let data={}
      for(let i =0;i<this.goodsCategory.length;i++){
        if(this.goodsCategory[i].id === id){
          return data={'id':this.goodsCategory[i].id,'name':this.goodsCategory[i].name}
        }
      }
      return
    },

    handleDeleteGoodsCategory(index, row) {
      this.couponCategoryList.splice(index, 1)
      this.LinkcouponCategoryList.splice(index,1)
    },
    handleDeleteforbidScope(index, row) {
      this.forbidScope.splice(index, 1)
      this.LinkforbidScope.splice(index,1)

    },
    getGoodsById(id) {
      for (let i = 0; i < this.goodsOptions.length; i++) {
        if (id === this.goodsOptions[i].goodsId) {
          return this.goodsOptions[i]
        }
      }
      return null
    },
    getCategoryList() {
      listCategory().then(response => {
        const list = response.data.data.list
        this.goodsCategoryOptions = []
        for (let i = 0; i < list.length; i++) {
          const children = []
          if (list[i].children != null && list[i].children.length > 0) {
            for (let j = 0; j < list[i].children.length; j++) {
              children.push({ label: list[i].children[j].name, value: list[i].children[j].id })
            }
          }
          this.goodsCategoryOptions.push({ label: list[i].name, value: list[i].id, children: children })
        }
      })
    },
    getGoodsCategoryByIds(ids) {
      let name
      let parentName
      for (let i = 0; i < this.goodsCategoryOptions.length; i++) {
        if (this.goodsCategoryOptions[i].value === ids[0]) {
          parentName = this.goodsCategoryOptions[i].label
          for (let j = 0; j < this.goodsCategoryOptions[i].children.length; j++) {
            if (this.goodsCategoryOptions[i].children[j].value === ids[1]) {
              name = this.goodsCategoryOptions[i].children[j].label
            }
          }
        }
      }
      return { goodsCategoryId: ids[1], goodsCategoryName: name, parentCategoryName: parentName }
    }
  }
}
</script>
